#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智慧童话世界 - 演示脚本
展示AI可选分支剧情童话书的核心功能
"""

import asyncio
import json
from pathlib import Path
import sys

# 添加当前目录到Python路径
sys.path.append(str(Path(__file__).parent))

from ai_fairy_tale_book import AIFairyTaleBook
from mcp_integration import initialize_mcp, get_mcp_instance
from zhiyuan_integration import initialize_zhiyuan, get_zhiyuan_instance

async def demo_story_generation():
    """演示故事生成功能"""
    print("\n🎭 === 故事生成演示 ===")
    
    # 初始化系统
    await initialize_mcp()
    await initialize_zhiyuan()
    
    # 创建AI童话书实例
    fairy_tale = AIFairyTaleBook()
    await fairy_tale.initialize()
    
    # 演示参数
    demo_params = {
        "theme": "勇敢与友谊",
        "age_group": "6-8",
        "child_name": "小明",
        "interests": ["动物", "冒险", "科学"]
    }
    
    print(f"📝 生成参数: {json.dumps(demo_params, ensure_ascii=False, indent=2)}")
    
    # 生成故事
    story_result = await fairy_tale.generate_story(**demo_params)
    
    if story_result["success"]:
        print(f"\n📚 生成的故事:")
        print(f"标题: {story_result['story']['title']}")
        print(f"内容: {story_result['story']['content']}")
        print(f"\n🔀 可选择的分支:")
        for i, choice in enumerate(story_result['story']['choices'], 1):
            print(f"{i}. {choice}")
    else:
        print(f"❌ 故事生成失败: {story_result.get('error', '未知错误')}")

async def demo_mcp_integration():
    """演示MCP集成功能"""
    print("\n📡 === MCP集成演示 ===")
    
    mcp = get_mcp_instance()
    
    # 演示教育内容生成
    content_result = await mcp.generate_educational_content(
        topic="数学加法",
        age_group="6-8"
    )
    
    if content_result["success"]:
        print(f"📚 教育内容: {content_result['content']}")
        print(f"🎯 相关概念: {', '.join(content_result['concepts'])}")
    
    # 演示多模态处理
    multimodal_data = {
        "text": "我想学习关于动物的故事",
        "image": b"fake_image_data",
        "audio": b"fake_audio_data"
    }
    
    processed_result = await mcp.process_multimodal_input(multimodal_data)
    
    if processed_result["success"]:
        print(f"\n🎨 多模态处理结果:")
        print(f"文本处理: {processed_result['processed_data']['text']['keywords']}")
        print(f"图像处理: {processed_result['processed_data']['image']['description']}")
        print(f"音频处理: {processed_result['processed_data']['audio']['transcription']}")

async def demo_zhiyuan_integration():
    """演示智源数据集成功能"""
    print("\n🧠 === 智源数据集成演示 ===")
    
    zhiyuan = get_zhiyuan_instance()
    
    # 演示学习建议
    recommendations = zhiyuan.get_learning_recommendations(
        age_group="6-8",
        topic="科学探索"
    )
    
    print(f"📊 学习建议:")
    print(f"词汇量限制: {recommendations['content_guidelines']['vocabulary_limit']}")
    print(f"最大句长: {recommendations['content_guidelines']['max_sentence_length']}")
    print(f"复杂度: {recommendations['content_guidelines']['complexity_level']}")
    print(f"注意力时长: {recommendations['content_guidelines']['session_duration']}分钟")
    
    print(f"\n🎯 参与策略:")
    for strategy in recommendations['engagement_strategies']:
        print(f"• {strategy}")
    
    # 演示学习进度分析
    user_data = {
        "age": 7,
        "performance_scores": {"math": 85, "reading": 78, "science": 92},
        "interactions": {"image_interactions": 15, "audio_interactions": 8, "choice_interactions": 22},
        "completed_topics": ["基础数学", "动物认知"],
        "target_curriculum": ["基础数学", "动物认知", "植物科学", "天文知识"]
    }
    
    progress_analysis = zhiyuan.analyze_learning_progress(user_data)
    
    print(f"\n📈 学习进度分析:")
    print(f"认知水平: {progress_analysis['cognitive_development']}")
    print(f"学习风格: {progress_analysis['learning_preferences']}")
    print(f"知识缺口: {', '.join(progress_analysis['knowledge_gaps'])}")
    print(f"个性化建议:")
    for rec in progress_analysis['recommendations']:
        print(f"• {rec}")

async def demo_interactive_story():
    """演示交互式故事体验"""
    print("\n🎮 === 交互式故事演示 ===")
    
    fairy_tale = AIFairyTaleBook()
    await fairy_tale.initialize()
    
    # 开始新故事
    story_result = await fairy_tale.generate_story(
        theme="神奇的森林",
        age_group="6-8",
        child_name="小红",
        interests=["动物", "魔法"]
    )
    
    if not story_result["success"]:
        print("❌ 故事生成失败")
        return
    
    current_story = story_result["story"]
    print(f"\n📖 {current_story['title']}")
    print(f"{current_story['content']}")
    
    # 模拟用户选择
    choices = current_story['choices']
    print(f"\n🔀 请选择:")
    for i, choice in enumerate(choices, 1):
        print(f"{i}. {choice}")
    
    # 模拟选择第一个选项
    selected_choice = choices[0]
    print(f"\n👆 你选择了: {selected_choice}")
    
    # 处理选择并生成后续故事
    choice_result = await fairy_tale.handle_choice(
        story_id=current_story.get('id', 'demo_story'),
        choice=selected_choice,
        user_context={"age_group": "6-8", "interests": ["动物", "魔法"]}
    )
    
    if choice_result["success"]:
        next_story = choice_result["next_story"]
        print(f"\n📖 故事继续...")
        print(f"{next_story['content']}")
        
        if next_story.get('choices'):
            print(f"\n🔀 新的选择:")
            for i, choice in enumerate(next_story['choices'], 1):
                print(f"{i}. {choice}")
    else:
        print(f"❌ 选择处理失败: {choice_result.get('error', '未知错误')}")

def print_demo_banner():
    """打印演示横幅"""
    banner = """
    ╔══════════════════════════════════════════════════════════════╗
    ║                🎪 智慧童话世界 - 功能演示 🎪                 ║
    ║                                                              ║
    ║  本演示将展示以下核心功能:                                    ║
    ║  🎭 AI故事生成                                               ║
    ║  📡 MCP集成功能                                              ║
    ║  🧠 智源数据应用                                             ║
    ║  🎮 交互式故事体验                                           ║
    ╚══════════════════════════════════════════════════════════════╝
    """
    print(banner)

async def main():
    """主演示函数"""
    try:
        print_demo_banner()
        
        # 运行各个演示
        await demo_story_generation()
        await demo_mcp_integration()
        await demo_zhiyuan_integration()
        await demo_interactive_story()
        
        print("\n🎉 === 演示完成 ===")
        print("💡 要体验完整的Web界面，请运行: python main.py")
        
    except Exception as e:
        print(f"❌ 演示过程中发生错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(main())